<?php
// 添加商品后端
header("content-type:text/html;charset=utf-8");
include_once("conn.php");
//设置默认时区
date_default_timezone_set('PRC');
$now_date = date('Y-m-d H:i:s');

$goods_id = date('YmdHis');
$goods_name = $_POST['goods_name'];
$goods_price = $_POST['goods_price'];
$goods_num = $_POST['goods_num'];
$goods_type = $_POST['goods_type'];
$goods_desc = $_POST['goods_describe'];
$goods_specs = $_POST['goods_specs'];
$goods_img = $_FILES['goods_img'];
$goods_img_name = $goods_img['name'];
$goods_img_size = $goods_img['size'];
$goods_img_tmp = $goods_img['tmp_name'];
$goods_img_type = $goods_img['type'];
$fileExtension = strtolower(pathinfo($goods_img_name, PATHINFO_EXTENSION));

if ($goods_img_size > 0) {
    // 判断文件类型
    if ($goods_img_type == 'image/jpeg' || $goods_img_type == 'image/png' || $goods_img_type == 'image/gif') {
        // 判断文件大小
        if ($goods_img_size <= 2097152) {
            // 生成新的文件名
            $goods_img_name = $goods_id . "." . $fileExtension;
            // 移动文件
            $res = move_uploaded_file($goods_img_tmp, '../../goods_imgs/' . $goods_img_name);
            if ($res) {
                // 将数据插入数据库
                $sql = "INSERT INTO tb_goods_info (g_id,g_name,g_price,g_num,g_type,g_img,g_describe,g_specs,g_adddate) 
                        VALUES('" . $goods_id . "','" . $goods_name . "','" . $goods_price . "','" . $goods_num . "','" . $goods_type . "','" . $goods_img_name . "','" . $goods_desc . "','" . $goods_specs . "','" . $now_date . "')";
                $result = mysqli_query($conn, $sql);
                if ($result) {
                    echo "<script>alert('添加成功');location.href='../a_add_goods.php'</script>";
                } else {
                    //插入失败则删除上传图
                    unlink('../../goods_imgs/' . $goods_img_name);
                    echo "<script>alert('添加失败');history.go(-1);</script>";
                }
            } else {
                echo "<script>alert('文件上传失败');history.go(-1);</script>";
            }
        } else {
            echo "<script>alert('文件大小不能超过2MB');history.go(-1);</script>";
        }
    } else {
        echo "<script>alert('文件类型不正确');history.go(-1);</script>";
    }
} else {
    echo "<script>alert('请选择文件');history.go(-1);</script>";
}
